﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace Note_Final_new
{
    public static class AccountService
    {
        private static readonly string AccountsFile = Path.Combine(
            Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
            "EnhancedNotes", "accounts.dat");

        // 注册新用户
        public static bool Register(string username, string password)
        {
            // 验证用户名合法性（防止目录遍历）
            if (string.IsNullOrWhiteSpace(username) || username.Contains("..") || username.Contains("/") || username.Contains("\\"))
                return false;

            // 创建用户目录
            string userDir = GetUserNotesDirectory(username);
            Directory.CreateDirectory(userDir);

            // 密码加盐哈希处理
            string salt = GenerateSalt();
            string hashedPassword = HashPassword(password, salt);

            // 追加写入账户文件
            using (var writer = new StreamWriter(AccountsFile, true))
            {
                writer.WriteLine($"{username}:{salt}:{hashedPassword}");
            }

            return true;
        }

        // 用户登录验证
        public static bool Login(string username, string password)
        {
            if (!File.Exists(AccountsFile)) return false;

            foreach (var line in File.ReadAllLines(AccountsFile))
            {
                var parts = line.Split(':');
                if (parts.Length == 3 && parts[0] == username)
                {
                    string salt = parts[1];
                    string storedHash = parts[2];
                    string inputHash = HashPassword(password, salt);
                    return storedHash == inputHash;
                }
            }
            return false;
        }

        // 获取用户专属笔记目录
        public static string GetUserNotesDirectory(string username)
        {
            string baseDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Notes");
            string userDirectory = Path.Combine(baseDirectory, username);
            Directory.CreateDirectory(userDirectory);
            return userDirectory;
        }

        // 生成随机盐值
        private static string GenerateSalt()
        {
            byte[] saltBytes = new byte[16];
            using (var rng = RandomNumberGenerator.Create())
            {
                rng.GetBytes(saltBytes);
            }
            return Convert.ToBase64String(saltBytes);
        }

        // 密码哈希处理
        private static string HashPassword(string password, string salt)
        {
            using (var sha256 = SHA256.Create())
            {
                byte[] saltedPassword = Encoding.UTF8.GetBytes(password + salt);
                byte[] hashBytes = sha256.ComputeHash(saltedPassword);
                return Convert.ToBase64String(hashBytes);
            }
        }
    }
}
